<?php

namespace App\Http\Controllers\Api\V1;

use Yansongda\Pay\Pay;
use App\Models\Course;
use App\Models\CourseUser;
use App\Models\CourseStudyLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Hhxsv5\LaravelS\Components\HttpClient\SimpleHttpTrait;

class CourseUserController extends BaseController
{
	use SimpleHttpTrait;
    /**
     *
     * 报名 学习
     * @param {Object} Request
     */
    public function add(Request $request)
    {
		$courseId = $request->get('course_id');
		$account = $request->get('account');
		$passwd = $request->get('passwd');
		$phone = $request->get('phone');
		$id = $request->get('id');
		
		$course = Course::where('id', $courseId)->first();
		
		//验证密码是否正确 
		$startParam = [
			'account' => $account,
			'passwd' => $passwd,
		];
		if($course){
			$startParam['task_class'] = $course['task_class'];
			$argsArr = json_decode($course['args'], true);
			foreach($argsArr as $k => $v){
				$startParam[$k] = $v;
			}
		}
		$taskIpport = env('COURSE_LEARN_TASK_IPPORT');
		$checkRet = $this->httpGet('http://'.$taskIpport.'/check_pwd?'.http_build_query($startParam), ['timeout' => 60]);
		\Log::info('check_pwd: '.\var_export($checkRet, true));
		if($checkRet && isset($checkRet['body'])){
			$checkResult = json_decode($checkRet['body'], true);
			if(isset($checkResult['is_ok']) && !$checkResult['is_ok']){
				return $this->returnFail('账号密码有误/你所在区域不可学，请确认');
			}
			// if(isset($checkResult['is_empty']) && $checkResult['is_empty']){
			// 	return $this->returnFail('你所在区域不可学，请确认');
			// }
		}
		
		$attributes = [
		    'course_id' => $courseId,
		    'account' => $account,
		    'pwd' => $passwd,
		];
		if($phone){
			$attributes['phone'] = $phone;
		}
		
		$detail = CourseUser::where('course_id', $courseId)->where('account', $account)->where('phone', $phone)->first();
		//\Log::info("$courseId $account $phone ret ".\var_export($detail, true));
		if($detail){
			$attributes['status'] = 0;
			$upRet = CourseUser::where('id', $detail['id'])->update($attributes);
			if($upRet){
				return $this->returnFail('已有对应账号，更新成功');
			}
			return $this->returnFail('已有对应账号，但更新失败');
		}
		
		
		$user = CourseUser::create($attributes);
		$data = $user->attributesToArray();
		
    	return $this->returnSuccess($data);
    }
	
	/**
	 *
	 * 获取用户的报名列表
	 * @param {Object} Request
	 */
	public function index(Request $request)
	{
		$courseId = $request->get('course_id', -1);
		$phone = $request->get('phone');
	    //当前页数 默认1
		$page = $request->get('page', 1);
		//每页的条数
		$perPage = 10;
		//计算每页分页的初始位置
		$offset = ($page * $perPage) - $perPage;
		$users = CourseUser::where('course_id', $courseId)->where('phone', $phone)->orderBy('id', 'desc')->paginate($perPage);
		
		$user = $this->user();
		 //实例化LengthAwarePaginator类，并传入对应的参数
		$dataArry = $users->toArray();
		
		foreach($dataArry['data'] as $index => $one){
			
		}
		$newsIds = isset($dataArry['data']) ? field_vals($dataArry['data'], 'id') : [];
		if($user && $user->id){
			
		}
		
		return $this->returnSuccess($dataArry);
	}
	
	/**
	 * 开始学习课程
	 * 
	 */
	public function learn(Request $request){
		$regId = $request->get('reg_id', 0);
		
		if(empty($regId)){
			return $this->returnFail('参数有误');
		}
		
		$cuser = CourseUser::where('id', $regId)->first();
		if(!$cuser){
			return $this->returnFail('无效的学习登记，请检测');
		}
		$cuserArr = $cuser->toArray();
		if(!$cuserArr['is_payed']){
			return $this->returnFail('您还未完成支付');
		}
		if(in_array($cuserArr['status'], [1])){
			return $this->returnFail('您当前正在学习');
		}
		if($cuserArr['finish_per'] >=100){
			return $this->returnFail('您的学习已完成');
		}
		
		$attributes = [
		    'reg_id' => $regId,
		];
		$record = CourseStudyLog::create($attributes);
		if(!$record){
			return $this->returnFail('创建学习记录失败');
		}
		$data = $record->toArray();
		// $courseInfo = CourseUser::where('id', $regId)->first();
		$startParam = [
			// 'account' => $courseInfo['account'],
			// 'passwd' => $courseInfo['pwd'],
			'courseStudyId' => $data['id'],
		];
		
		$course = Course::where('id', $cuser['course_id'])->first();
		
		$courseArr = $course->toArray();
		\Log::info('course: '.\var_export($courseArr, true));
		if($courseArr && isset($courseArr['task_class']) && $courseArr['task_class']){
			$startParam['task_class'] = $courseArr['task_class'];
		}
		if(isset($courseArr['args']) && $courseArr['args']){
			$args = is_array($courseArr['args']) ? $courseArr['args'] : json_decode($courseArr['args'], true);
			if($args){
				foreach($args as $key => $val){
					$startParam[$key] = $val;
				}
			}
		}
		
		
		$taskIpport = env('COURSE_LEARN_TASK_IPPORT');
		$response = $this->httpGet('http://'.$taskIpport.'/start?'.http_build_query($startParam), ['timeout' => 3]);
		
		\Log::info('httpGet response: '.\var_export($response, true));
		//标记
		
		$data = $record->toArray();
		return $this->returnSuccess($data);
	}
}
